/* eslint-disable camelcase */

import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import Button from '@kuiper-components/button';
import Switch from '@kuiper-components/switch';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import notification from '@kuiper-components/notification';
import Tooltip from '@kuiper-components/tooltip';
import Dialog from '@knownsec/react-component/dist/Dialog';
import { Spin } from 'antd';
import confirm from '../../../../components/confirm';
import EmptyData from '../../../../components/empty/EmptyData';
import Content from './Content/Content';
import Input from '@knownsec/react-component/dist/Input';
import { filterNull } from '../../../../../common/validation/common';
import CopyBoard from '../../../../components/CopyBoard';

import { withRouter } from 'react-router';

import s from './AlertGroup.module.css';
import icon from './icon.png';
import fetchFer from 'API/fetch';
const defaultFilter = {
	page: 1,
	count: 10,
	name: '',
	target_url: '',
	source_ip: '',
};
const turnToUrlParams = obj => {
	let urls = '';
	const hasValKey = Object.keys(obj)
		.filter(item => obj[item] || obj[item] === false || obj[item] === 0)
		.map(i => {
			return i + '=' + obj[i];
		});
	urls = hasValKey.join('&');
	return urls;
};
const alertOptions = {
	email: '邮件',
	sms: '短信',
	wechat: '微信',
	in_box: '站内信',
};
function AlertGroup({ className, history }) {
	const prefilter = new URLSearchParams(location.search).get('filter');
	const filterS = prefilter ? JSON.parse(prefilter) || {} : {};
	const defaultFilter_ = { ...defaultFilter, ...filterS };
	const [filter, setFilter] = React.useState(defaultFilter_);
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const [loading, setLoading] = React.useState(true);
	const [tableData, setTableData] = React.useState([]);
	const [total, setTotal] = React.useState(0);
	const [jobList, setJobList] = React.useState([]);
	const [jobLoading, setJobLoading] = React.useState(true);
	const [jobShow, setJobShow] = React.useState(false);
	const [formText, setFormText] = React.useState('');
	const [dialogRecord, setDialogRecord] = React.useState(false);
	const [balanceData, setBalanceData] = React.useState({ used: 0, residue: 0 });
	const columns = [
		{
			title: '策略名称',
			dataIndex: 'name',
			key: 'name',
			render(val) {
				return (
					<div title={val}>
						<CopyBoard text={val} maxWidth="11rem" />
					</div>
				);
			},
		},
		{
			title: '告警人',
			dataIndex: 'alert_receivers',
			key: 'alert_receivers',
			width: 80,
			render(alert_receivers) {
				return (
					<Tooltip
						placement="top"
						overlayClassName={s.overlay}
						overlay={
							<div className={cn(s.tableConatiner, className)}>
								<table className={s.table}>
									<thead>
										<tr className={s.head}>
											<td>告警人名称</td>
											<td>手机</td>
											<td>邮箱</td>
										</tr>
									</thead>
									<tbody>
										{alert_receivers?.map(item => (
											<tr className={s.row} key={item._id}>
												<td>{item.name}</td>
												<td>{item.phone || '- -'}</td>
												<td>{item.email || '- -'}</td>
											</tr>
										))}
									</tbody>
								</table>
							</div>
						}
					>
						<span className={s.receivers}>
							{alert_receivers.length}人
							<img src={icon} className={s.img} />
						</span>
					</Tooltip>
				);
			},
		},
		{
			title: '告警资产',
			dataIndex: 'job_count',
			key: 'job_count',
			width: 100,
			render(job_count, record) {
				return (
					<>
						<span className={s.jobsNum}>{job_count}个</span>
						{job_count > 0 && (
							<span
								className={s.main_text}
								onClick={() => {
									showJobList(record.id);
								}}
							>
								详情
							</span>
						)}
					</>
				);
			},
		},
		{
			title: '通知类型',
			dataIndex: 'notification',
			key: 'notification',
			render(notification, record) {
				const type = notification.map(e => {
					return alertOptions[e];
				});
				const text = type.join('、');
				return <>{text || '- -'}</>;
			},
		},
		{
			title: '告警开关',
			dataIndex: 'enable',
			key: 'enable',
			render(enable, record) {
				return (
					<Switch
						checked={enable}
						onClick={enable => {
							changeSwitch(enable, record);
						}}
					/>
				);
			},
		},
		{
			title: '操作',
			dataIndex: 'enable',
			key: 'actions',
			render(enable, record) {
				return (
					<div className={s.actions}>
						<Button
							primary
							link
							className={s.btn}
							onClick={() => {
								setFormText('修改告警策略');
								setDialogRecord(record);
							}}
						>
							修改
						</Button>
						{!record?.is_default && (
							<Button
								primary
								link
								className={cn(s.btn, s.ml16)}
								onClick={() => handleRemoveMany([record.id])}
							>
								删除
							</Button>
						)}
					</div>
				);
			},
		},
	];
	const columnsJod = [
		{
			title: '资产名称',
			dataIndex: 'note',
			width: 100,
			key: 'note',
			render(val) {
				return (
					<div title={val}>
						<CopyBoard text={val} maxWidth="11rem" />
					</div>
				);
			},
		},
		{
			title: '资产地址',
			dataIndex: 'target_url',
			key: 'target_url',
			width: 100,
			render(val) {
				return (
					<div title={val}>
						<CopyBoard text={val} maxWidth="11rem" />
					</div>
				);
			},
		},
		{
			title: '源站IP',
			dataIndex: 'source_ip',
			key: 'source_ip',
			render(val) {
				return <div title={val}>{val || '- -'}</div>;
			},
		},
	];
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const getList = async (e = {}) => {
		setDialogRecord(null);
		setLoading(true);
		let params = { ...filter, ...e };
		params = turnToUrlParams(params);
		const url = `/api/v2/alerts/alert_strategy_list?${params}`;
		const res = await fetchFer(url, {
			method: 'GET',
			checkStatus: 501,
		}).catch(() => {
			return {};
		});
		if (res.data.results.length < 1 && e.page > 1) {
			setFilter({ ...filter, count: 10, page: e.page - 1 });
			getList({ count: 10, page: e.page - 1 });
			return false;
		}
		if (res.status === 'success') {
			res.data.results.forEach(e => {
				e.key = e.id;
			});
			setTotal(res.data.count);
			setTableData(res.data.results);
		}
		setLoading(false);
		// 更新套餐
		const resB = await fetchFer('/api/v2/users/balance/get', {
			method: 'GET',
		});
		const {
			balance: { alertGroup },
		} = resB.results;
		const residue_ = alertGroup.total - alertGroup.used;
		setBalanceData({
			total: alertGroup.total,
			used: alertGroup.used,
			residue: residue_ <= 0 ? 0 : residue_,
		});
		sessionStorage.setItem('resD', JSON.stringify(resB.results));
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
		getCheckboxProps: record => ({
			disabled: record.is_default,
		}),
	};
	const handleRemoveMany = receivers => {
		confirm.warning({
			message: (
				<span>删除告警策略行为不可逆，您确认要删除选择的告警策略吗？</span>
			),
			okText: '删除',
			cancelText: '取消',
			onCancel: () => {
				setSelectedRowKeys([]);
			},
			onOk: async () => {
				const res = await fetchFer(`/api/v2/alerts/delete_alert_strategy`, {
					method: 'POST',
					body: JSON.stringify({
						alert_group_ids: receivers,
					}),
				});
				if (res.status === 'success') {
					notification.success({
						message: `删除成功`,
						placement: 'top',
					});
					getList();
				} else {
					notification.error({
						message: '删除失败',
						description: res.message,
						placement: 'top',
					});
				}
			},
		});
	};
	const changeSwitch = (enable, record) => {
		let text = '关闭此告警策略将停止对策略里所有资产告警通知，您确定要关闭？';
		enable &&
			(text = '开启此告警策略将对策略里所有资产进行告警通知，您确定要开启？');
		confirm.warning({
			message: <span>{text}</span>,
			title:'',
			okText: '确定',
			cancelText: '取消',
			onOk: () => {
				alertSwitch(record, enable);
			},
		});
	};
	const alertSwitch = async (record, enable) => {
		const res = await fetchFer(`/api/v2/alerts/alert_strategy_switch`, {
			method: 'POST',
			body: JSON.stringify({
				alert_group_id: record.id,
				switch: enable,
			}),
		});
		if (res.status === 'success') {
			notification.success({
				message: `操作成功`,
				placement: 'top',
			});
			getList();
		} else {
			notification.error({
				message: '修改告警策略状态失败',
				description: res.message,
				placement: 'top',
			});
		}
	};
	const showJobList = async id => {
		setJobShow(true);
		setJobLoading(true);
		const res = await fetchFer(
			`/api/v2/alerts/alert_strategy_jobs?alert_group_id=${id}`,
			{
				method: 'GET',
			}
		);
		setJobList(res.data);
		setJobLoading(false);
	};
	const handleChangeSearch = e => {
		if (e === 'r') {
			getList(defaultFilter);
			setFilter(defaultFilter);
		} else {
			if (e) {
				getList(e);
			} else {
				getList();
			}
		}
	};
	React.useEffect(() => {
		getList();
	}, []);
	return (
		<div className={cn(className, s.alertGroup)}>
			<div className={s.toolbox}>
				<Button
					primary
					disabled={!('total' in balanceData)}
					onClick={() => {
						if (balanceData.residue <= 0) {
							notification.error({
								message: '当前套餐告警策略已达到上限，无法继续添加。',
								placement: 'top',
							});
							return;
						}
						setFormText('新建告警策略');
						setDialogRecord(null);
					}}
				>
					新建告警策略
				</Button>
				<div className={s.balanceDescription}>
					您当前已创建<mark>{balanceData.used}</mark>个告警策略，还可创建
					<mark>{balanceData.residue}</mark>
					个告警策略。
				</div>
				<div className={s.searchBox}>
					<Input
						search={true}
						normalSearch={true}
						value={filter.name}
						className={s.searchBtn}
						placeholder="请输入策略名称"
						onChange={({ value }) => {
							setFilter({ ...filter, name: value, page: 1, count: 10 });
						}}
						onSearch={({ value }) => {
							handleChangeSearch();
						}}
					/>
					<Input
						search={true}
						className={s.searchBtn}
						normalSearch={true}
						value={filter.target_url}
						placeholder="请输入资产地址"
						onChange={({ value }) => {
							setFilter({
								...filter,
								target_url: value,
								page: 1,
								count: 10,
							});
						}}
						onSearch={({ value }) => {
							handleChangeSearch();
						}}
					/>
					<Input
						search={true}
						normalSearch={true}
						className={s.searchBtn}
						value={filter.source_ip}
						placeholder="请输入源站IP"
						onChange={({ value }) => {
							setFilter({
								...filter,
								source_ip: value,
								page: 1,
								count: 10,
							});
						}}
						onSearch={({ value }) => {
							handleChangeSearch();
						}}
					/>
					<Button
						className={s.btn}
						onClick={() => {
							// setFilter(defaultFilter);
							handleChangeSearch('r');
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<div className={s.mt1rem}>
				<Table
					key={Date.now()}
					pro
					empty={<EmptyData type={'img'} className={s.nobor} />}
					loading={loading}
					className={s.newtable}
					columns={columns}
					data={tableData}
					rowSelection={rowSelection}
				/>
			</div>
			<div className={cn('df aic jcsb mt5')} style={{paddingRight: '24px'}}>
				<Button
					link
					className={s.batchRemove}
					disabled={!selectedRowKeys.length}
					onClick={() => handleRemoveMany(selectedRowKeys)}
				>
					批量删除
				</Button>
				{total > 10 && (
					<Pagination
						current={filter.page || 1}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						total={total}
						onChange={(page, count) => {
							setFilter({ ...filter, page, count });
							handleChangeSearch({ page, count });
						}}
					/>
				)}
			</div>
			<Dialog
				visible={jobShow}
				onhide={() => setJobShow(false)}
				title="告警资产详情"
				cancelText=""
				confirmText="确认"
				className={cn(s.w800)}
			>
				<Spin spinning={jobLoading}>
					<div className={cn(s.p20)}>
						<Table
							key={Date.now()}
							// pro
							empty={<EmptyData type={'img'} className={s.nobor} />}
							// loading={jobLoading}
							columns={columnsJod}
							data={jobList}
						/>
					</div>
				</Spin>
			</Dialog>
			<Dialog
				visible={formText}
				key={Date.now()}
				onhide={() => setFormText(false)}
				title={formText}
				cancelText=""
				confirmText=""
				className={cn(s.w800)}
			>
				{formText && (
					<Content
						onClose={() => setFormText(false)}
						record={dialogRecord}
						isDefault={dialogRecord?.is_default}
						submit={() => {
							setFormText(false);
							getList();
						}}
					/>
				)}
			</Dialog>
		</div>
	);
}

AlertGroup.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func,
		replace: PropTypes.func,
	}),
};

AlertGroup.defaultProps = {
	className: s.AlertGroup,
};
export default withRouter(AlertGroup);
